package cn.enilu.flash.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

public class IpUtils {
    private static final List<String> HEADERS_TO_TRY = Arrays.asList(
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR"
    );

/**
 * 获取客户端IP地址的方法
 * 该方法会依次检查多个HTTP头，以获取真实的客户端IP地址
 *
 * @param request HttpServletRequest对象，包含请求信息
 * @return 返回客户端IP地址字符串
 */
    public static String getClientIpAddress(HttpServletRequest request) {
    // 遍历预设的HTTP头列表，这些头可能包含客户端IP地址
        for (String header : HEADERS_TO_TRY) {
        // 从请求中获取指定头的值
            String ip = request.getHeader(header);
        // 检查IP是否有效（非空、非空字符串、不是"unknown"）
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                // X-Forwarded-For 可能包含多个 IP，取第一个
                if (header.equalsIgnoreCase("X-Forwarded-For")) {
                    int commaIndex = ip.indexOf(',');
                    if (commaIndex != -1) {
                        ip = ip.substring(0, commaIndex);
                    }
                }
                return ip.trim();
            }
        }
        // 最后 fallback 到 remoteAddr
        return request.getRemoteAddr();
    }
}
